
const http = require("http");
const socketIO = require("socket.io");

let httpServer = http.createServer();
let socketIOServer = socketIO(httpServer);

let clientDict = { };

function broadcast (uuid, msg) {
    let myClient = clientDict[uuid];
    if (myClient) {
        let nickName = myClient.nickName;
        for (cuuid in clientDict) {
            clientDict[cuuid].client.emit("getmsg", nickName + "：" + msg);
        }
    }
}

function broadcastSys (msg) {
    for (cuuid in clientDict) {
        clientDict[cuuid].client.emit("getmsg", "系统提示：" + msg);
    }
}

socketIOServer.on("connection", (client) => {
    let uuid;
    let nickName;
    client.on("uuid", (res) => {
        uuid = res;
        console.log("新 uuid 访问：" + uuid);
        clientDict[uuid] = new Object();
        clientDict[uuid].client = client;
    });
    client.on("nickname", (res) => {
        nickName = res;
        console.log(uuid + " 注册了昵称：" + nickName);
        clientDict[uuid].nickName = nickName;
        broadcastSys(nickName + " 来到聊天室");
    });
    client.on("sendmsg", (res) => {
        let msg = res;
        broadcast(uuid, msg);
    });
});

socketIOServer.listen(1024);